package com.zjw.zy.coreui.fragment.wechat

import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.baidu.mapapi.model.LatLng
import com.zjw.zy.R
import com.zjw.zy.base.BaseFragment
import com.zjw.zy.base.BaseRecyclerAdapter
import com.zjw.zy.bean.WsMessage
import com.zjw.zy.constant.C2CMessageInfo
import com.zjw.zy.constant.ImageSubPath
import com.zjw.zy.constant.WechatMessageSubInfo
import com.zjw.zy.coreui.fragment.adapter.WechatListAdapter
import com.zjw.zy.coreui.fragment.holder.WechatMessageHolder
import com.zjw.zy.coreui.view.ImageViewContent
import com.zjw.zy.coreui.view.WechatInputView
import com.zjw.zy.ext.*
import com.zjw.zy.setting.SettingStorage
import com.zjw.zy.setting.WechatBackgroundPathOption
import com.zjw.zy.utils.*
import com.zjw.zy.viewmodel.SettingViewModel
import com.zjw.zy.viewmodel.WsMessageDispatchViewModel
import com.zjw.zy.voice.VoiceService
import com.zjw.zy.wsmessage.IC2CMessageHandler
import map.utils.MapUtils

/**
 * @author     ：zhong.jw
 * @date       ：Created in 2022/12/4 22:19
 * @description：
 */
class WechatFragment : BaseFragment(), IC2CMessageHandler {

    companion object {
        private const val TAG = "WechatFragment"
    }

    private val wsMessageDispatchViewModel: WsMessageDispatchViewModel by activityViewModels()

    private val settingViewModel: SettingViewModel by activityViewModels()

    private val mAdapter =
        WechatListAdapter(object : BaseRecyclerAdapter.ItemListener<WechatMessageHolder> {
            override fun onCallbackOtherEvent(event: String, vararg args: Any?) {
                when (event) {
                    WechatMessageHolder.EVENT_CLICK_IMAGE -> {
                        handleClickImage(args[0] as String)
                    }
                }
            }
        })

    private val mList: RecyclerView by lazy { findViewById(R.id.wechat_list) }
    private val mInput: WechatInputView by lazy { findViewById(R.id.wechat_input) }

    private val mLayoutManager: RecyclerView.LayoutManager = LinearLayoutManager(context)


    private fun handleClickImage(path: String) {
        goImagePreview(PathUtils.getPrivateImagePath(ImageSubPath.WECHAT_IMAGE_MESSAGE), path)
    }

    override fun onPageEnter() {
        WindowUtils.TopBar.hideAllRightButton()
        WindowUtils.TopBar.showTopBarNav()
        WindowUtils.TopBar.hideBack()
        WindowUtils.TopBar.hideNav()
        WindowUtils.FootBar.show()

        SettingStorage.getOption(WechatBackgroundPathOption::class.java)?.let {
            mainActivity().setFullBackGround(
                BitmapDrawable(
                    resources,
                    PathUtils.getBitmapFromPath(it.value)
                )
            )
        } ?: kotlin.run {
            //todo 默认
            mainActivity().setFullBackGround(ResourcesUtils.getDrawable(R.drawable.my_love_1))
        }

        wsMessageDispatchViewModel.startPingLove()
        updateName()
    }

    override fun onBackClick() {
        super.onCallMoveToBack()
    }

    override fun onPageCreate() {
        super.onPageCreate()
        wsMessageDispatchViewModel.requireWechatMessages()
    }

    override fun onViewRestore(savedInstanceState: Bundle?) {

    }

    override fun onSubscribe() {

        settingViewModel.getSelfName().observe(this) {
            updateName()
        }

        settingViewModel.getLoverName().observe(this) {
            updateName()
        }

        settingViewModel.getWechatBackgroundPathOption().observe(this) { option ->
            option?.let {
                mainActivity().setFullBackGround(
                    BitmapDrawable(
                        resources,
                        PathUtils.getBitmapFromPath(option.value)
                    )
                )
            } ?: kotlin.run {
                //todo 默认
                mainActivity().setFullBackGround(ResourcesUtils.getDrawable(R.drawable.my_love_1))
            }

        }

        wsMessageDispatchViewModel.getWechatMessages().observe(this) {
            mAdapter.notifyDataWithDiff(it)
            scrollToLast()
        }

        wsMessageDispatchViewModel.getWechatMessage().observe(this) {
            mAdapter.insertMessage(it)
            scrollToLast()
        }

        wsMessageDispatchViewModel.getPingPong().observe(this) { pingPong ->
            //更新ui
            if (pingPong) {
                WindowUtils.TopBar.show1RightButton(ResourcesUtils.getDrawable(R.drawable.icon_location)) {
                    //查看对方位置
                    wsMessageDispatchViewModel.send(WsMessage.obtainC2C(C2CMessageInfo.QUERY_LOCATION))
                }
                WindowUtils.TopBar.show2RightButton(ResourcesUtils.getDrawable(R.drawable.icon_telephone)) {
                    mainActivity().startForegroundService(Intent().apply {
                        action = VoiceService.SERVICE_ACTION
                        `package` = mainActivity().packageName
                        //发起者
                        putExtra(VoiceService.CONNECT_TYPE, VoiceService.CONNECT_SENDER_TYPE)
                    })
                    //请求语音通话
                    wsMessageDispatchViewModel.send(WsMessage.obtainC2C(C2CMessageInfo.VOICE_CONNECT_REQUEST))
                }
            } else {
                WindowUtils.TopBar.show1RightButton(ResourcesUtils.getDrawable(R.drawable.icon_location_offline)) {
                    "对方未在线".longToast()
                }
                WindowUtils.TopBar.show2RightButton(ResourcesUtils.getDrawable(R.drawable.icon_telephone_offline)) {
                    "对方未在线".longToast()
                }
            }
        }
    }

    private fun updateName() {
        WindowUtils.TopBar.setTopBarLabelText(
            ResourcesUtils.getString(
                R.string.wechat_fragment_label,
                settingViewModel.getLoverName().value?.value ?: AppUtils.getLove()!!.name,
                settingViewModel.getSelfName().value?.value ?: AppUtils.getSelf()!!.name,
            )
        )
    }

    override fun onBindViewListener() {

        mInput.bindListener(object : WechatInputView.Listener {
            override fun onCompleteText(str: String) {
                wsMessageDispatchViewModel.sendWechatMessage(str)
            }

            override fun onPickUpClick() {
                pickUpImage() {
                    val text = GsonUtils.toJson(PathUtils.getBitmapFromPath(it)?.toByteArray())
                    wsMessageDispatchViewModel.sendWechatMessage(text, WechatMessageSubInfo.IMAGE)
                }
            }

            override fun onFuncClick() {
            }
        })
    }

    override fun onBindViewValue() {
        mList.adapter = mAdapter
        mList.layoutManager = mLayoutManager
    }

    override fun onFindView(rootView: View?) {

    }

    override fun onLayoutId(): Int {
        return R.layout.wechat_fragment
    }

    override fun onPageExit() {
        wsMessageDispatchViewModel.stopPingLove()
    }


    private fun scrollToLast() {
        mLayoutManager.scrollToPosition(mAdapter.data.size - 1)
    }

    override fun onInterception(info: String): Boolean {
        return info == C2CMessageInfo.QUERY_LOCATION_REPAIR || info == C2CMessageInfo.VOICE_CONNECT_REQUEST
                || info == C2CMessageInfo.VOICE_CONNECT_ACCEPT
    }

    override fun onHandleC2CMessage(message: WsMessage) {
        //展示位置哦
        when (message.info) {
            C2CMessageInfo.QUERY_LOCATION_REPAIR -> {
                MapUtils.startMap(GsonUtils.fromJson(message.text, LatLng::class.java))
            }
        }
    }
}